package demo2接口使用案例;

import java.util.Comparator;

/*class Student implements Comparable<Student>{//当我们要比较自定义类型大小时，要实现这个Comparable接口
    public String name;
    public int age;
    public Student(String name,int age) {
        this.age = age;
        this.name = name;
    }
    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public int compareTo(Student o) {
        //return this.age-o.age; 等于下面写的代码

        if(this.age>o.age){
            return 1;
        }else if(this.age<o.age){
            return -1;
        }else {
            return 0;
        }
    }
}*/




class Student  {//当我们要比较自定义类型大小时，要实现这个Comparable接口
    public String name;
    public int age;

    public Student(String name, int age) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

class AgeCompareto implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        return o1.age-o2.age;
    }
}


class NameCompareto implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);//因为string类型在源码里比较调用的是compareTo方法
    }
}





public class Test {
    public static void main(String[] args) {
        Student student1 = new Student("张三",10);
        Student student2 = new Student("李四",15);

       AgeCompareto ageCompareto = new AgeCompareto();
        System.out.println(ageCompareto.compare(student1, student2));


        NameCompareto nameCompareto = new NameCompareto();
       nameCompareto.compare(student1,student2);
        System.out.println(nameCompareto.compare(student1,student2));

    }

    public static void bubbleSort(Comparable[] comparables){
        for (int i = 0; i < comparables.length-1; i++) {
            for (int j = 0; j < comparables.length-1-i; j++) {
                if(comparables[j].compareTo(comparables[j+1])>0){
                    Comparable tmp = comparables[j];
                    comparables[j] = comparables[j+1];
                    comparables[j+1] = tmp;
                }
            }
        }
    }

    public static void main1(String[] args) {

//        Student student1 = new Student("张三",10);
//        Student student2 = new Student("李四",15);
//
//        System.out.println(student1.compareTo(student2));//student1.age<student2.age比较

        Student[] students = new Student[3];
        students[0] = new Student("张三",10);
        students[1] = new Student("李四",8);
        students[2] = new Student("王五",15);

        /*Arrays.sort(students);
        System.out.println(Arrays.toString(students));*/

//        bubbleSort(students);
//        System.out.println(Arrays.toString(students));



    }


}
